<template>
  <section class="msg_send">
    <template v-if="groupInfo?.alertSubdivideType === 500 || (stopSendMsg && !isMaster)">
      <section class="stopMsg">{{ stopSendMsg }}</section>
    </template>
    <template v-else>
      <p class="quite" v-if="showQuote && seleteUserCardInfo.content">
        <i>{{ seleteUserCardInfo?.nickName }}</i>
        <i>:</i>
        <i v-html="passText(seleteUserCardInfo?.content)" class="quite_msg_conetnt"></i>
        <el-icon class="close" @click="$emit('update:showQuote', false)">
          <CircleClose />
        </el-icon>
      </p>
      <textarea wrap="soft" v-model="text" cols="30" rows="1" class="send" placeholder="请输入新消息"
        @keypress="sendMsgAction"></textarea>
      <div class="msg_space">
        <el-popover placement="top" :width="370" trigger="click" :teleported="false" :persistent="false">
          <template #reference>
            <img src="local-media://icons/emoj.png" alt="">
          </template>
          <section class="emoji">
            <img v-for="num in 58" :src="`local-media://emoji/emoji_${num}@3x.png`" alt=""
              @click="text += `[f0${num < 10 ? ('0' + num) : num}]`">
          </section>
        </el-popover>
        <div class="times">
          <el-icon @click="openFileAction" style="color:#c3c3c3;font-size: 23px;" v-if="!fileLoading">
            <PictureRounded />
          </el-icon>
          <el-icon class="is-loading" style="color:#c3c3c3;font-size: 23px;" v-else title="正在上传">
            <Loading />
          </el-icon>
        </div>
        <button class="sendBtn" @click="send">发送</button>
      </div>
    </template>
  </section>
</template>
<script setup>
import { ref, computed, defineProps } from 'vue';
import { sendMessage, sendGroupMessage, updateFile } from '@/server/friend'
import { useRequest } from 'vue-hooks-plus';
import { useStore } from 'vuex';
import { v4 as uuidv4 } from 'uuid';
import { handelNotice } from '@/tool/useWebsokect'
import useLiveQuery from '@/tool/useLiveQuery';
import { groupState } from '@/tool'
import { db } from '@/config/data'
import { ElMessage } from 'element-plus'
const fs = require('fs');
const props = defineProps({
  row: {
    type: Object,
    default: () => ({})
  },
  seleteUserCardInfo: {
    type: Object,
    default: () => ({})
  },
  showQuote: {
    type: Boolean,
    default: () => false
  }
})
const emit = defineEmits(['update:showQuote'])
const store = useStore()
const userInfo = computed(() => store.state.userInfo)
const selectSession = computed(() => store.state.selectSession)
const text = ref('')
const customInitMsg = async ({ value, type, msgId }) => {
  const customMsg = {
    msgId,
    pushType: "MSG",
    timestamp: new Date().getTime(),
    msgContent: {
      content: value?.trim(),
      disturb: selectSession.value.disturb,
      msgType: type,
      top: selectSession.value.top
    },
    fromInfo: {
      nickName: userInfo?.value?.nickName,
      portrait: userInfo?.value?.portrait,
      userId: userInfo?.value?.userId,
      userType: userInfo?.value?.userType || '',
    },
    groupInfo: {
      nickName: selectSession.value?.groupName,
      portrait: selectSession.value?.groupPortrait,
      userId: selectSession.value?.groupId,
    },
    uuid: props?.row?.uuid
  }
  if (selectSession.value?.msgCustomType === 0) customMsg.groupInfo = {}
  await handelNotice(customMsg, store)
}

const groupInfo = useLiveQuery(() => db.groupInfo.get({ uuid: props?.row?.uuid }), [props.row])
const stopSendMsg = computed(() => groupInfo.value && Reflect.get(groupState, groupInfo.value?.alertSubdivideType))
const isMaster = computed(() => groupInfo.value && (groupInfo.value.administrator === 'Y' || groupInfo.value.master === "Y"))

const passText = (str) => {
  try {
    const result = JSON.parse(str)
    if (result?.content) {
      str = result.content
    }
  } catch (error) {
  }
  str = String(str)
  Array.from(new Array(59)).forEach((v, r) => {
    const t = `[f0${r < 10 ? ('0' + r) : r}]`
    if (str?.includes(t)) {
      str = str.replaceAll(t, `<img src="local-media://emoji/emoji_${r}@3x.png" class='emoji' style='width:20px;height:20px;'/>`)
    }
  })
  const hasNotice = str.includes('群公告\n')
  if (hasNotice) str = str.replaceAll('群公告\n', '群公告<br/>')
  if (str.startsWith('http')) str = `<img src="${str}" class='quote_img' style="object-fit: cover;"/>` //一张图片
  return str
}
const { runAsync: sendMsg } = useRequest((params) => {
  return selectSession.value?.msgCustomType === 1 ? sendGroupMessage(params) : sendMessage(params)
}, {
  onSuccess: async (res, [params]) => {
    await customInitMsg({ value: params?.content, type: params?.msgType, msgId: params.msgId })
    if (params?.msgType === 'TEXT') {
      text.value = ''
      emit('update:showQuote', false)
    }
  },
  manual: true,
  onError: async (err) => {
    if (err?.code === 500 && selectSession.value.msgCustomType === 1 && err?.msg === '你不在当前群中') {
      const item = await db.groupInfo.get({ uuid: selectSession.value.uuid })
      if (item) return await db.groupInfo.update(item.id, { alertSubdivideType: 500 })
      await db.groupInfo.add({ alertSubdivideType: 500, administrator: "N", uuid: selectSession.value.uuid })
      return
    }
    ElMessage({
      type: 'error',
      message: err.msg || '网络连接失败',
      center: true,
    })
  },
  onFinally: () => {
    fileLoading.value = false
  }
})
const fileLoading = ref()
const openFile = async (file) => {
  if (!file) return
  const data = new FormData()
  data.append('file', file)
  const res = await updateFile(data)
  if (res) {
    const msgId = uuidv4()
    const params = {
      userId: selectSession.value?.userId,
      msgType: 'IMAGE',
      content: res?.fullPath,
      msgId,
    }
    const groupMsg = {
      groupId: selectSession.value?.groupId,
      msgType: 'IMAGE',
      content: res?.fullPath,
      msgId,
    }
    const p = selectSession.value?.msgCustomType === 1 ? groupMsg : params
    await sendMsg(p)
  }
}
const submitMsg = async () => {
  const msgId = uuidv4()

  const params = {
    userId: selectSession.value?.userId,
    msgType: 'TEXT',
    content: text.value,
    msgId,
  }
  const groupMsg = {
    groupId: selectSession.value?.groupId,
    msgType: 'TEXT',
    content: text.value,
    msgId,
  }

  if (props.showQuote) {
    //引用
    let callText = ''
    try {
      const str = props.seleteUserCardInfo?.content
      const result = JSON.parse(str)
      callText = result?.content || str
    } catch (error) {
      callText = props.seleteUserCardInfo?.content
    }
    let content = {
      msgName: props.seleteUserCardInfo?.nickName,
      msgId: props.seleteUserCardInfo?.msgId,
      content: text.value,
      msgText: callText //防止套娃
    }
    content = JSON.stringify(content)
    groupMsg.content = content
    params.content = content
  }
  const p = selectSession.value?.msgCustomType === 1 ? groupMsg : params
  await sendMsg(p)
}
const sendMsgAction = async (e) => {
  if (e.keyCode == 13) {
    e.preventDefault()
    if (text.value?.trim() === '') return false
    await submitMsg()
  }
  return false
}
const send = async () => {
  if (text.value?.trim() === '') return false
  await submitMsg()
}

const openFileAction = async () => {
  try {
    const res = await window.electronAPI.openFile()
    if (res !== undefined) {
      fileLoading.value = true
      const path = res[0]
      const content = fs.readFileSync(path)
      const file = new File([content], path.split("\\").reverse()[0], { type: 'image/' + path.split('.').reverse()[0] })
      await openFile(file)
    }
  } catch (error) {

  }
}
const editText = (value) => {
  text.value = value
}
</script>

<style scoped lang="less">
.msg_send {
  width: 100%;
  height: 132px;
  background: #FFFFFF;
  flex-shrink: 0;
  display: flex;

  .send {
    flex: 1;
    border: none;
    outline: none;
    padding-top: 20px;
    padding-left: 17px;
    font-size: 14px;
    font-weight: 400;
    letter-spacing: 1px;
    line-height: 16px;
    user-select: none;
    resize: none;

    &::-webkit-scrollbar {
      display: none;
    }
  }

  .msg_space {
    padding-top: 15px;
    display: flex;
    padding-right: 10px;
    position: relative;

    >img {
      width: 22px;
      height: 22px;
      margin-left: 20px;
    }

    .times {
      width: 22px;
      height: 22px;
      position: relative;
      margin-left: 20px;

      >input {
        opacity: 0;
        position: absolute;
        left: 0;
        top: 0;
        bottom: 0;
        right: 0;
        z-index: 1;
      }
    }
  }
}

.emoji {
  width: 100%;
  display: grid;
  grid-template-columns: repeat(10, 1fr);
  grid-gap: 10px;

  >img {
    width: 25px;
    height: 25px;
    cursor: pointer;
  }
}

.sendBtn {
  position: absolute;
  right: 20px;
  bottom: 10px;
  width: 120px;
  height: 40px;

  border-radius: 30px;
  border: none;
  background: linear-gradient(114deg, #f4f4f4 8%, #f4f4f4 100%);
  letter-spacing: 5px;
  cursor: pointer;
  color: #242424;
  transition: all 0.1s;

  &:hover {
    background: linear-gradient(114deg, #009BFD 8%, #00E8E8 100%);
    color: #FFF;
  }
}

.stopMsg {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  user-select: none;
}

.quite {
  position: absolute;
  bottom: 10px;
  margin-left: 20px;
  font-size: 14px;
  line-height: 30px;
  max-width: 50%;
  height: 30px;
  overflow: hidden;
  background-color: #eee;
  padding-right: 25px;
  padding-left: 10px;
  display: flex;
  align-items: center;

  .close {
    position: absolute;
    right: 5px;
    transform: translateY(-50%);
    top: 50%;
    font-size: 16px;
    cursor: pointer;
  }

  :deep(.quote_img) {
    max-height: 30px;
    object-fit: cover;
    margin: 0 5px;
  }

  .quite_msg_conetnt {
    img {
      max-height: 100%;
      object-fit: cover;

    }
  }
}
</style>
